package middleware

import (
	"bytes"
	"dlxGoProject/global"
	"dlxGoProject/pkg/logger"
	"github.com/gin-gonic/gin"
	"time"
)

type AccessLogWriter struct {
	gin.ResponseWriter
	body *bytes.Buffer
}

func (w AccessLogWriter) Wtire(p []byte) (int, error) {
	if n,err:=w.body.Write(p);err!=nil{
		return n, err
	}
	return w.ResponseWriter.Write(p)
}

func AccessLog() gin.HandlerFunc {
	return func(c *gin.Context) {
		bodyWrite:=&AccessLogWriter{
			ResponseWriter: c.Writer,
			body:           bytes.NewBufferString(""),
		}
		c.Writer=bodyWrite
		beginTime:=time.Now().Unix()
		c.Next()
		endTime:=time.Now().Unix()
		fields:=logger.Fields{
			"request": c.Request.PostForm.Encode(),
			"response":bodyWrite.body.String(),
		}
		s:="access log: method: %s, status_code: %d, begin_time: %s, end_time: %s"
		global.Logger.WithFields(fields).Infof(c,s,c.Request.Method,bodyWrite.Status(),beginTime,endTime)
	}
}